<?php

class Kupon extends CI_Controller {

    function __construct() {
        parent::__construct();
		
        $this->load->model('tbl_product_model');
        $this->load->model('picture_product_model');
        $this->load->model('checkout_model');
        $this->load->model('order_model');
        $this->load->model('order_list_model');
        $this->load->model('user_ci_model');
		$this->load->model('tbl_coupon_model');
		
		$session_id = $this->session->userdata('session_id');
       
    }

    function index() {
         $config = array(
            'base_url' => site_url() . '/product/',
            'total_rows' => $this->db->count_all('tbl_product'),
            'per_page' => 5,
            'uri_segment'=>4
        );
        $this->pagination->initialize($config);
        $data['content'] = 'main';
        $data['pagination'] = $this->pagination->create_links();
        $data['tbl_products'] = $this->tbl_product_model->get_all($config['per_page'], $this->uri->segment(4));
		
			//$this->session->unset_userdata('guestid');
		if($this->session->userdata('guestid')==FALSE){
			$guestid = $this->session->userdata('session_id').'_'.$this->session->userdata('ip_adress').'_'.$this->session->userdata('user_agent');
			$this->session->set_userdata('guestid',$guestid);
		}
		echo $this->session->userdata('ip_adress');
        $this->load->view('template_default', $data);
    }

    function product() {
		$config = array(
            'base_url' => site_url() . '/product/',
            'total_rows' => $this->db->count_all('tbl_product'),
            'per_page' => 5,
            'uri_segment'=>4
        );
        $this->pagination->initialize($config);
        $data['content'] = 'product';
        $data['pagination'] = $this->pagination->create_links();
        $data['tbl_products'] = $this->tbl_product_model->get_all($config['per_page'], $this->uri->segment(4));
        $this->load->view('template_default', $data);
    }
	
	function product_detail($product_id){
		$config = array(
        
            array(
                'field' => 'product_id',
                'label' => 'Product ID',
                'rules' => 'required'
            ),
            
            array(
                'field' => 'quantity',
                'label' => 'Quantity',
                'rules' => 'required|greater_than[0]'
            ),
            
            array(
                'field' => 'product_name',
                'label' => 'Product Name',
                'rules' => 'required'
            ),
            
            array(
                'field' => 'price',
                'label' => 'Product Price',
                'rules' => 'required'
            ),
        );
        $this->form_validation->set_rules($config);
		$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
		
		if($this->form_validation->run()==TRUE){
			if($this->input->post('add')==TRUE){
				$data = array(
					'product_id' => $this->input->post('product_id'),
					'product_name' => $this->input->post('product_name'),
					'quantity' => $this->input->post('quantity'),
					'price' => $this->input->post('price'),
					'cus_id_temp' => $this->session->userdata('guestid')
				);
				//var_dump($data);
				
				//check product dah ada dak lagi
				$ck_chart = $this->checkout_model->get_where(array('product_id' => $data['product_id'],
					'cus_id_temp' => $data['cus_id_temp']));
				if($ck_chart->num_rows()==1){
					$qty = $ck_chart->row()->quantity + $data['quantity'];
					$this->checkout_model->update(
						array('quantity' => $qty), 
						array('product_id' => $data['product_id'], 
							'cus_id_temp' => $data['cus_id_temp'])
					);
							
					//echo $qty;
				}else{
					$cartadd = $this->checkout_model->add($data);
					$cart = $this->checkout_model->get_where(array('cus_id_temp' => $data['cus_id_temp']));
					
				}
				
            	$this->session->set_flashdata('notif', 'Cart has been updated');
			}
		}
		
		$data['product'] = $this->tbl_product_model->get_one($product_id);
		$data['content'] = 'product_detail';
		$this->load->view('template_default', $data);
	}
	
	function checkout() {
		
		$data['checkout'] = $this->checkout_model->get_where(array('cus_id_temp' => $this->session->userdata('guestid')));		
        $data['content'] = 'checkout';
        $this->load->view('template_default', $data);
    }

//insert cart
	function cartinsert(){
		$config = array(
        
            array(
                'field' => 'product_id',
                'label' => 'Product id',
                'rules' => 'required'
            ),
            
            array(
                'field' => 'product_name',
                'label' => 'Product Name',
                'rules' => 'required'
            ),
            
            array(
                'field' => 'price',
                'label' => 'Price',
                'rules' => 'required'
            ),
            
            array(
                'field' => 'quantity',
                'label' => 'Quantity',
                'rules' => 'required'
            ),
            
        );
        $this->form_validation->set_rules($config);
		
        if ($this->form_validation->run() == TRUE) {
 			if($this->input->post('product_id')){
				
				$data = array(
					   'product_id' => $this->input->post('product_id'),
					   'quantity'     => $this->input->post('quantity'),
					   'price'   => $this->input->post('price'),
					   'product_name'    => $this->input->post('product_name'),
					   'cus_id_temp' => $this->input->post('cus_id_temp')
					);
				//$this->input->post('product_id');
				//$this->cart->insert($data); 
				
				//check product dah ada dak lagi
				$ck_chart = $this->checkout_model->get_where(array('product_id' => $data['product_id'],
					'cus_id_temp' => $data['cus_id_temp']));
				if($ck_chart->num_rows()==1){
					$qty = $ck_chart->row()->quantity + $data['quantity'];
					$this->checkout_model->update(
						array('quantity' => $qty), 
						array('product_id' => $data['product_id'], 
							'cus_id_temp' => $data['cus_id_temp'])
					);
							
					echo $qty;
				}else{
					$cartadd = $this->checkout_model->add($data);
					$cart = $this->checkout_model->get_where(array('cus_id_temp' => $data['cus_id_temp']));
					foreach($cart->result_array() as $row){
						echo $row['product_name'].' '.$row['price'].' '.$row['quantity'];
					}
				}
				
            	$this->session->set_flashdata('notif', 'Data has been inserted');
			
				redirect('kupon/product');
			}
		}
	}
	
	//delete cart
	function cartdelete($id = ''){
		$data = array('rowid' => $id,
			'qty' => 0);
		//var_dump($data);
		//$this->cart->update($data); 
		$this->checkout_model->delete(array('id' => $id));
		$this->session->set_flashdata('notif', 'Data has been deleted');
		redirect('kupon/checkout');
	}
	
	//update cart
	function cartupdate(){
		$tarikh = date('Y-m-d H:i:s', now());
		if($this->input->post('update')==TRUE){
			foreach($_POST['rowid'] as $key => $val){
				$data[$key]= array(
					'id' => $_POST['rowid'][$key],
					'quantity' => $_POST['quantity'][$key],
					'price' => $_POST['price'][$key]
				);
				$this->checkout_model->update(
					array('quantity' => $_POST['quantity'][$key]),
					array('id' => $_POST['rowid'][$key])); 
			}
			$this->session->set_flashdata('notif', 'Data has been updated');
			redirect('kupon/checkout');
		}
		//$this->cart->update($data);
		if($this->input->post('pay')==TRUE){
			
			foreach($_POST['rowid'] as $key => $val){
					$data[$key]= array(
						//'id' => $_POST['rowid'][$key],
						'product_id' => $this->input->post('product_id')[$key],
						'quantity' => $_POST['quantity'][$key],
						'price' => $_POST['price'][$key],
						'customer_id' => $this->session->userdata('guestid')
					);					
				}
				//echo $this->session->userdata('guestid');
			//var_dump($data);
			$this->order_list_model->add_batch($data);
			//exit();
			
			$dataorder['total_price'] = $this->input->post('total_price');
			$dataorder['status'] = 'order';
			$dataorder['customer_id'] = $this->session->userdata('guestid');
			$dataorder['order_date'] = date('Y-m-d H:i:s', now());
				
			if($this->input->post('coupon_code')==TRUE){
				
				//var_dump($data);
				//echo 'ada kupon';
				$dataorder['coupon_code'] = $this->input->post('coupon_code');
				$dataorder['coupon_value'] = $this->input->post('diskaun');
				//$dataorder['jenis_diskaun'] = $this->input->post('jenis_diskaun');
				$dataorder['total_price'] = $this->input->post('total_price');
				$dataorder['diskaun_price'] = $this->input->post('diskaun_price');
				$dataorder['date_edit'] = $tarikh;
				$dataorder['status'] = 'order';
				$dataorder['customer_id'] = $this->session->userdata('guestid');
				$this->order_model->add($dataorder);
				$data['order_id'] = $this->order_model->last_insert_id('order_model');
				$this->order_list_model->update(array('order_id' => $data['order_id']), array('customer_id' => $dataorder['customer_id']));
				
				//check total used
				$coupon = $this->tbl_coupon_model->get_where(array('coupon_code' => $dataorder['coupon_code']));
				$total_used = $coupon->row()->total_used + 1;
				$this->tbl_coupon_model->edit(array('total_used' => $total_used), array('coupon_code' => $dataorder['coupon_code']));
				
			}else{
				//echo 'xdak diskaun';
				//var_dump($dataorder);
				$this->order_model->add($dataorder);
				$data['order_id'] = $this->order_model->last_insert_id('order_model');
				$this->order_list_model->update(array('order_id' => $data['order_id']), array('customer_id' => $dataorder['customer_id']));
			}
			
			
			
			//clear checkpout
			$this->checkout_model->delete(array('cus_id_temp' => $dataorder['customer_id']));
			
			$this->postto($data);
		}
	}
	
	//clear/destroy cart items
	function cartdestroy(){
		
	}
	
	function ajaxkupon(){
		$id = $this->input->post('coupon_code');
		$data = $this->tbl_coupon_model->get_where(array('coupon_code' => $id));
		//$data = $this->tbl_coupon_model->get_all(5, $this->uri->segment(4));
		//foreach($data->result_array() as $key){
			//$nilai_kupon = $key['nilai_coupon'];
		//}
		$total_price = $this->input->post('total_price');
		$now = date('Y-m-d',now());
		if($data->num_rows()>0){
			if(strtotime($data->row()->start_date) <= strtotime($now) && strtotime($data->row()->expired_date) >= strtotime($now)){
				if($data->row()->minimum_price <= $this->input->post('total_price')){
					if($data->row()->limit_coupon_used >> $data->row()->total_used){
						if($data->row()->jenis_coupon == 'percent'){
							//echo $data->row()->nilai_coupon.'%';
							$total_price = $total_price * (100 - $data->row()->nilai_coupon) / 100;
							$arraydata = array(
								'diskaun' => $data->row()->nilai_coupon.'%',
								'message' => 'You got discount '.$data->row()->nilai_coupon.'%<input type="hidden" name="diskaun" value="'.$data->row()->nilai_coupon.'%"/><input type="hidden" name="jenis_diskaun" value="percent"/>',
								'total_price' => $total_price);
						}
						if($data->row()->jenis_coupon == 'nilai'){
							//echo 'RM '.$data->row()->nilai_coupon;
							$total_price = $total_price - $data->row()->nilai_coupon;
							$arraydata = array(
								'diskaun' => 'RM '.number_format($data->row()->nilai_coupon,2),
								'message' => 'You got discount RM '.$data->row()->nilai_coupon.'<input type="hidden" name="diskaun" value="RM '.$data->row()->nilai_coupon.'"/><input type="hidden" name="jenis_diskaun" value="nilai"/>',
								'total_price' => $total_price);
						}
					}else{
						$message = 'Already reached limit used';
						$arraydata = array('diskaun' => NULL,
							'message' => $message,
							'total_price' => $total_price);
							//break;
					}
				}else{
					$message = 'Your purchases must be more than '.$data->row()->minimum_price;
					$arraydata = array(
								'diskaun' => NULL,
								'message' => $message,
								'total_price' => $total_price);
								//break;
				}
			}else{
				$message = "Coupon already espired";
				$arraydata = array(
								'diskaun' => NULL,
								'message' => $message,
								'total_price' => $total_price);
								//break;
			}
		}else{
			$message = "Coupon doesn't exist";
			$arraydata = array(
							'diskaun' => NULL,
							'message' => $message,
							'total_price' => $total_price);
		}
		echo json_encode($arraydata);
	}
	
	//post data
	function postTo($data = NULL){
		
		$config = array(
        
            array(
                'field' => 'icno',
                'label' => 'IC Number',
                'rules' => 'required'
            ),
            
            array(
                'field' => 'fname',
                'label' => 'First Name',
                'rules' => 'required'
            ),
            
            array(
                'field' => 'lname',
                'label' => 'Last Name',
                'rules' => 'required'
            ),
            
            array(
                'field' => 'address',
                'label' => 'Address',
                'rules' => 'required'
            ),
			
            array(
                'field' => 'phone',
                'label' => 'Phone Number',
                'rules' => 'required'
            ),
            
            array(
                'field' => 'email',
                'label' => 'Email',
                'rules' => 'required|valid_email'
            ),
            
            array(
                'field' => 'order_id',
                'label' => '',
                'rules' => ''
            ),
        );
        $this->form_validation->set_rules($config);
		
		//var_dump($data);
		$this->order_model->get_where(array('id' => $data['order_id']));
		$this->order_list_model->get_where(array('order_id' => $data['order_id']));
		
		if ($this->form_validation->run() == TRUE){
			if($this->input->post('confirm')==TRUE){
				$datauser['icno'] = $this->input->post('icno');
				$datauser['username'] = $this->input->post('icno');
				$datauser['fname'] = $this->input->post('fname');
				$datauser['lname'] = $this->input->post('lname');
				$datauser['address'] = $this->input->post('address');
				$datauser['phone'] = $this->input->post('phone');
				$datauser['email'] = $this->input->post('email');
				$data['order_id'] = $this->input->post('order_id');
				
				//check user
				$user = $this->user_ci_model->get_where(array('icno' => $datauser['icno']));
				if($user->num_rows()==0){
					$this->user_ci_model->add($datauser);
					//echo 'add user';
				}else{
					$this->user_ci_model->edit(array('icno' => $this->input->post('icno'),
						'fname' => $this->input->post('fname'),
						'lname' => $this->input->post('lname'),
						'address' => $this->input->post('address'),
						'phone' => $this->input->post('phone'),
						'email' => $this->input->post('email')), array('icno' => $datauser['icno']));
				}
				
				
				$this->order_model->update(array('customer_id' => $datauser['icno']), array('id' => $data['order_id']));
				$this->order_list_model->update(array('customer_id' => $datauser['icno']), array('order_id' => $data['order_id']));
				
				/*$this->load->library('email');
	
				$this->email->from('your@example.com', 'Your Name');
				$this->email->to($datauser['email']);
				//$this->email->cc('another@another-example.com');
				//$this->email->bcc('them@their-example.com');
				
				$this->email->subject('Email Test');
				$this->email->message('Testing the email class.');
				
				$this->email->send();
				
				echo $this->email->print_debugger();*/
				$this->session->set_flashdata('notif', 'Data has been updated');
				redirect('kupon/order/'.$data['order_id']); 
			}
		}
		

		
		$data['content'] = 'payment'; //page
        $this->load->view('template_default', $data);
		
	}
	
	function ajaxuser(){
		$ic = $this->input->post('icno');
		$user = $this->user_ci_model->get_where(array('icno' => $ic));
		if($user->num_rows()==1){
			$data = array('fname' => $user->row()->fname, 
			'lname' => $user->row()->lname,
			'address' => $user->row()->address,
			'phone' => $user->row()->phone,
			'email' => $user->row()->email);
		}else{
			$data = array('fname' => '', 
				'lname' => '',
				'address' => '',
				'phone' => '',
				'email' => '');
		}
		echo json_encode($data);
	}
	
	function order($order_id = ''){		
			
		$data['order'] = $this->order_model->get_where(array('id'=>$order_id));
		$data['order_list'] = $this->order_list_model->get_where(array('order_id' => $order_id));
		$data['user'] = $this->user_ci_model->get_where(array('icno' => $data['order']->row()->customer_id));
		
		
		$data['content'] = 'order'; //page
        $this->load->view('template_default', $data);

	}
}
?>
